﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS发运计划卡控及更新
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMtoTMSShipPlanCheckController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;


        public CRMtoTMSShipPlanCheckController(ILogger<CRMtoTMSShipPlanCheckRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            _logger = loggerFactory.CreateLogger<CRMtoTMSShipPlanCheckController>();

        }

        /// <summary>
        /// TMS发运计划卡控及更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostCRMPlanCheck([FromBody] CRMtoTMSShipPlanCheckRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSShipping_PlanCreate_2ResponseDto re = new TMSShipping_PlanCreate_2ResponseDto();
            string create_type = strparm.create_type;

            if (strparm.create_type==""|| strparm.create_type==null)
            {
                strMsg = "create_type不能为空";
            }

            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            Dictionary<string, string> plandic = new Dictionary<string, string>(); //计划表插入dic
            try
            {
                if (strMsg=="")
                {
                    foreach (var item in strparm.rows)
                    {
                        if (item.plan_no == "" || item.plan_no == null)
                        {
                            strMsg = strMsg + "plan_no不能为空！-";
                        }
                        else
                        {
                            dic = new Dictionary<string, string>(); //查询发货计划流水记录数据
                            dic.Add("ccode", item.plan_no);
                            DataTable check_dt = MethodHelp.GetTableInfo("TMS0161", dic, con);
                            if (check_dt.Rows.Count <= 0)
                            {
                                //忽略找不到计划明细记录情况
                                //strMsg = strMsg + "plan_no=<" + item.plan_no + ">找不到计划单号记录，请确认后再试！-";
                            }
                            else
                            {
                                if (strparm.create_type=="Update")
                                {
                                    if (DB.ToDouble(item.cancel_qty) > (DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString())-DB.ToDouble(check_dt.Rows[0]["yfpmount"].ToString())))
                                    {
                                        strMsg = strMsg + "plan_no=<" + item.plan_no + ">取消数量=<"+ item.cancel_qty + ">大于剩余可分配数量<"+ (DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString()) - DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString()))+">";
                                    }
                                    else
                                    {
                                        double materialamount = DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString()) - DB.ToDouble(item.cancel_qty);
                                        dic = new Dictionary<string, string>(); //更新发货计划数量
                                        dic.Add("ccode", item.plan_no);
                                        dic.Add("materialamount", materialamount.ToString());
                                        strMsg = MethodHelp.InsertIntoTable("TMS0162", dic,con);
                                    }
                                }
                                else
                                {
                                    if (DB.ToDouble(item.cancel_qty) > (DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString()) - DB.ToDouble(check_dt.Rows[0]["yfpmount"].ToString())))
                                    {
                                        strMsg = strMsg + "plan_no=<" + item.plan_no + ">取消数量=<" + item.cancel_qty + ">大于剩余可分配数量<" + (DB.ToDouble(check_dt.Rows[0]["materialamount"].ToString()) - DB.ToDouble(check_dt.Rows[0]["yfpmount"].ToString())) + ">";
                                    }
                                }
                            }
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
